package com.zjp.baseDemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjp.baseDemo.domain.ResponseResult;
import com.zjp.baseDemo.domain.eneity.LoginUser;
import com.zjp.baseDemo.domain.eneity.User;
import com.zjp.baseDemo.domain.vo.UserInfoVo;
import com.zjp.baseDemo.domain.vo.UserLoginVo;
import com.zjp.baseDemo.mapper.UserMapper;
import com.zjp.baseDemo.service.LoginService;
import com.zjp.baseDemo.utils.BeanCopyUtils;
import com.zjp.baseDemo.utils.JwtUtil;
import com.zjp.baseDemo.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;

import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authentication=authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authentication)){
            throw new RuntimeException("用户名或密码错误");
        }
        //获去userId ,生成token
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String token = JwtUtil.createJWT(userId);
        //存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        UserLoginVo userLoginVo=new UserLoginVo(token,userInfoVo);
        return ResponseResult.okResult(userLoginVo);
    }
}
